import cv2
import numpy as np

#图像读取、转为灰度图、二值化处理
img = cv2.imread("img1.jpg",1)
gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
rt,thresh = cv2.threshold(gray_img,240,255,cv2.THRESH_BINARY_INV)

#腐蚀
kernel = np.ones(shape=[3,3],dtype=np.uint8)
er = cv2.erode(thresh,kernel)

#检测轮廓
contours,hierarchy=cv2.findContours(er,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

draw_img=img.copy()
obj_type = ""
cor = 0

#遍历轮廓
for contour in contours:

    #过滤小轮廓
    if cv2.contourArea(contour)<=100:
        continue

    #轮廓近似
    epsilon = 0.02*cv2.arcLength(contour,True)
    approx = cv2.approxPolyDP(contour,epsilon,True)
    
    #判断图形
    cor = approx.shape[0]
    if cor == 3:
        obj_type = "Tri"
    
    elif cor == 4:
        obj_type = "Squ"
    
    elif cor > 4:
        obj_type = "Cir"

    #绘制轮廓
    cv2.drawContours(draw_img,contour,-1,(0,0,255),1)

    #绘制外框
    x,y,w,h = cv2.boundingRect(approx)
    cv2.rectangle(draw_img,(x,y),(x+w,y+h),(0,0,0),2)

    #绘制图形名称
    font=cv2.FONT_HERSHEY_SIMPLEX
    cv2.putText(draw_img,obj_type,(x,y-2), font, 0.6,(0,0,255),1)

#展示
cv2.imshow("img",draw_img)
cv2.waitKey(0)
